#pragma once
#include <sys/ipc.h>
#include <sys/shm.h>
#include<unistd.h>
#include<iostream>
#include<string>
const char *gfilename = "/home/liuzhi/linux_lesson/lesson/lesson11/sharemem";
const int gprojId = 0x1111;
const int gshmsize = 4096;
mode_t gmode = 0600;
class ShareMemory
{
private:
void CreateShmHelper(int flagmode)
{
    _key=ftok(gfilename,gprojId);
    if(_key<0)
    {
        std::cerr<<"ftok error"<<std::endl;
        return ;
    }
    _shmid=shmget(_key,gshmsize,flagmode);
    if(_shmid<0)
    {
        std::cerr<<"shmget error"<<std::endl;
        return ;
    }
    return;
}
public:
    ShareMemory():_key(0),_shmid(-1),_ret(nullptr)
    {
    }
    ~ShareMemory()
    {
    }
    void CreateShm()
    {
        CreateShmHelper(IPC_CREAT|IPC_EXCL|gmode);
    }
    void GetShm()
    {
        CreateShmHelper(IPC_CREAT|gmode);
    }
    void AttachShm()
    {
        _ret=shmat(_shmid,nullptr,0);
        if((long long) _ret==-1) 
        {
            std::cerr<<"attach error"<<std::endl;
            return;
        }
        std::cout<<"attach done"<<std::endl;
        return;
    }
    void DetachShm()
    {
        ::shmdt(_ret);
       
    }
    void DeleteShm()
    {
        ::shmctl(_shmid,IPC_RMID,nullptr);
    }
    void* getaddr()
    {
        return _ret;
    }
private:
    int _shmid;
    void* _ret;
    int _key;
};
ShareMemory share;


struct data
{
    char status[32];
    char lasttime[48];
    char image[4000];
};